-- ============================================
-- MACHINE A SOUS - ComputerCraft / CC:Tweaked
-- Nécessite : Advanced Computer + Advanced Monitor (couleur)
-- ============================================

-- === CONFIGURATION ===
local SYMBOLS = {
    { symbol = "\3",  color = colors.red,      value = 2,  name = "Coeur" },
    { symbol = "\4",  color = colors.yellow,   value = 3,  name = "Carreau" },
    { symbol = "\5",  color = colors.orange,   value = 5,  name = "Trefle" },
    { symbol = "\6",  color = colors.green,    value = 8,  name = "Pique" },
    { symbol = "\15", color = colors.lightBlue, value = 15, name = "Soleil" },
    { symbol = "7",   color = colors.magenta,  value = 50, name = "Sept" },
}

local MISE = 1
local balance = dofile("balance.lua")
local points = balance.load()

-- === PERIPHERIQUES ===
local mon = peripheral.find("monitor")
if not mon then
    error("Aucun monitor trouve ! Colle un Advanced Monitor a cote du computer.")
end

mon.setTextScale(0.5)
local prevTerm = term.redirect(mon)
local w, h = term.getSize()

local function centerText(y, text, textColor, bgColor)
    term.setBackgroundColor(bgColor or colors.black)
    term.setTextColor(textColor or colors.white)
    local x = math.floor((w - #text) / 2) + 1
    term.setCursorPos(x, y)
    term.write(text)
end

local function fillArea(x1, y1, x2, y2, bg)
    term.setBackgroundColor(bg)
    for y = y1, y2 do
        term.setCursorPos(x1, y)
        term.write(string.rep(" ", x2 - x1 + 1))
    end
end

-- === GEOMETRIE DES ROULEAUX ===
local REEL_COUNT = 3
local SYM_W, SYM_H = 7, 3   -- taille d'une case symbole
local SEP_H = 1              -- hauteur de la barre entre symboles
local REEL_GAP = 2

local totalReelWidth = REEL_COUNT * SYM_W + (REEL_COUNT - 1) * REEL_GAP
local reelsLeft = math.max(1, math.floor((w - totalReelWidth) / 2) + 1)
local reelsTop = 6

local function reelX(i)
    return reelsLeft + (i - 1) * (SYM_W + REEL_GAP)
end

-- Position Y des 3 cases visibles (haut / payline / bas) et des barres separatrices
local rowTopY = reelsTop
local sep1Y = rowTopY + SYM_H
local rowMidY = sep1Y + SEP_H
local sep2Y = rowMidY + SYM_H
local rowBotY = sep2Y + SEP_H
local reelBottom = rowBotY + SYM_H - 1

local function randomSymbol()
    return math.random(1, #SYMBOLS)
end

-- === DESSIN D'UN ROULEAU ===
local function drawSymbolBox(x1, y1, idx, isPayline)
    local sym = SYMBOLS[idx]
    local x2 = x1 + SYM_W - 1
    local y2 = y1 + SYM_H - 1
    term.setBackgroundColor(colors.black)
    for y = y1, y2 do
        term.setCursorPos(x1, y)
        term.write(string.rep(" ", SYM_W))
    end
    term.setTextColor(sym.color)
    local midY = y1 + math.floor(SYM_H / 2)
    local midX = x1 + math.floor((SYM_W - 1) / 2)
    term.setCursorPos(midX, midY)
    term.write(sym.symbol)

    if isPayline then
        term.setTextColor(colors.yellow)
        term.setCursorPos(x1, midY)
        term.write(">")
        term.setCursorPos(x2, midY)
        term.write("<")
    end
end

local function drawSeparator(x1, y, isPayline)
    term.setBackgroundColor(colors.black)
    term.setTextColor(isPayline and colors.yellow or colors.gray)
    term.setCursorPos(x1, y)
    term.write(string.rep("-", SYM_W))
end

local function drawReel(i, reel)
    local x = reelX(i)
    drawSymbolBox(x, rowTopY, reel.top, false)
    drawSeparator(x, sep1Y, true)   -- barre au-dessus de la payline (mise en valeur)
    drawSymbolBox(x, rowMidY, reel.mid, true)
    drawSeparator(x, sep2Y, true)   -- barre en-dessous de la payline
    drawSymbolBox(x, rowBotY, reel.bot, false)
end

local function drawAllReels(reels)
    for i, reel in ipairs(reels) do
        drawReel(i, reel)
    end
end

local function drawHeader(message, msgColor)
    fillArea(1, 1, w, reelsTop - 1, colors.black)
    centerText(1, "=== CASINO COMPUTERCRAFT ===", colors.yellow)
    centerText(2, "MACHINE A SOUS", colors.white)
    centerText(3, "Points : " .. points, colors.lime)
    if message then
        centerText(4, message, msgColor or colors.white)
    end
end

local function drawFooter(text, textColor)
    fillArea(1, reelBottom + 1, w, h, colors.black)
    if text then
        centerText(reelBottom + 2, text, textColor or colors.lightGray)
    end
end

-- === ANIMATION DE PLUIE DE DOLLARS (sur gain) ===
local function dollarRain(ticks)
    local drops = {}
    for i = 1, 12 do
        drops[i] = { x = math.random(1, w), y = math.random(-10, 0) }
    end

    for t = 1, ticks do
        for _, d in ipairs(drops) do
            term.setBackgroundColor(colors.black)
            term.setCursorPos(d.x, d.y)
            term.write(" ")
            d.y = d.y + 1
            if d.y > h then
                d.x = math.random(1, w)
                d.y = math.random(-6, 0)
            elseif d.y >= 1 then
                term.setTextColor(colors.lime)
                term.setCursorPos(d.x, d.y)
                term.write("$")
            end
        end
        sleep(0.06)
    end

    for _, d in ipairs(drops) do
        term.setBackgroundColor(colors.black)
        term.setCursorPos(d.x, math.min(d.y, h))
        term.write(" ")
    end
end

-- === LOGIQUE DE GAIN ===
local function evaluateWin(i1, i2, i3)
    if i1 == i2 and i2 == i3 then
        return SYMBOLS[i1].value * MISE, "JACKPOT ! 3x " .. SYMBOLS[i1].name
    elseif i1 == i2 or i2 == i3 or i1 == i3 then
        local matchIdx = (i1 == i2) and i1 or ((i2 == i3) and i2 or i1)
        return math.floor(SYMBOLS[matchIdx].value / 2), "Petit gain ! 2x " .. SYMBOLS[matchIdx].name
    else
        return 0, nil
    end
end

-- === UNE MANCHE ===
local function playRound()
    if points < MISE then
        drawHeader("PLUS ASSEZ DE POINTS !", colors.red)
        sleep(2)
        return
    end
    points = points - MISE
    balance.save(points)

    -- initialise 3 rouleaux avec des symboles aleatoires
    local reels = {}
    for i = 1, REEL_COUNT do
        reels[i] = { top = randomSymbol(), mid = randomSymbol(), bot = randomSymbol() }
    end

    local stopTicks = { 14, 20, 26 } -- chaque rouleau s'arrete l'un apres l'autre
    local maxTick = stopTicks[REEL_COUNT]

    drawHeader()
    drawFooter("Les rouleaux tournent...")

    for tick = 1, maxTick do
        for i, reel in ipairs(reels) do
            if tick <= stopTicks[i] then
                reel.top = reel.mid
                reel.mid = reel.bot
                reel.bot = randomSymbol()
            end
        end
        drawAllReels(reels)
        sleep(0.04 + tick * 0.004)
    end

    local i1, i2, i3 = reels[1].mid, reels[2].mid, reels[3].mid
    local gain, message = evaluateWin(i1, i2, i3)
    points = points + gain
    balance.save(points)

    drawHeader()

    if gain > 0 then
        drawFooter(message .. " (+" .. gain .. ")", colors.lime)
        dollarRain(20)
        drawAllReels(reels)
        drawHeader()
        drawFooter(message .. " (+" .. gain .. ")", colors.lime)
    else
        drawFooter("Perdu... reessaie !", colors.red)
    end

    sleep(1.5)
end

-- === PROGRAMME PRINCIPAL ===
local function drawIdle()
    term.setBackgroundColor(colors.black)
    term.clear()
    local reels = { {top=1,mid=1,bot=1}, {top=2,mid=2,bot=2}, {top=3,mid=3,bot=3} }
    drawHeader()
    drawAllReels(reels)
    drawFooter("Touche l'ecran pour miser " .. MISE .. " point et tirer !")
end

drawIdle()

while true do
    local event = os.pullEvent("monitor_touch")
    playRound()
    drawIdle()
end